<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box" style="height: 100%">
    <div class="content-box2">
      <a-tabs v-model:activeKey="currentTab" @change="changeTabData">
        <a-tab-pane v-for="item in tabData" :key="item.itemName" :tab="item.itemName"></a-tab-pane>
      </a-tabs>
    </div>
    <div v-if="currentTab == 'CCSS存用量图'">
      <Detail :chart="chart"></Detail>
    </div>
    <div v-else>
      <div class="content-box">
        <a-card class="common-card" :title="`${currentBtn}的数据`">
          <BasicTable @register="registerTable">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction :actions="createActions(record)" />
              </template>
            </template>
          </BasicTable>
        </a-card>
      </div>
    </div>
  </PageWrapper>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, watch, defineProps, defineEmits } from 'vue';
import { DatePicker } from 'ant-design-vue';
import { PageWrapper } from '@/components/Page';
import Icon from '@/components/Icon/Icon.vue';
import { BasicTable, useTable, TableAction } from '@/components/Table';
import { cloneDeep, head } from 'lodash-es';
import TotalTable from './totalTable.vue';
import { selectCcssEmissionData, ccssEmissionAddOrUpdate } from '@/api/common/chart';
import {
  getTgmplanNumDataSyn
} from '@/api/power/airConditioning/dailyUsage';
import { getDictListByCode } from '@/api/sys/dict';
import dayjs, { Dayjs } from 'dayjs';
import { useMessage } from '@/hooks/web/useMessage';
import Detail from '../Detail.vue';

const chart = 'gas_tgm_consumption_chart';
const tabData = ref();
const currentTab = ref();
const dateList = reactive([]);
const currentEditKeyRef = ref('');
const dateMonthValue = ref(dayjs());
const currentBtn = ref('Arry');
const classifyId = ref('');
const year2 = ref<dayjs[]>([dayjs(), dayjs()]);
const exportLoading = ref(false);
const emit = defineEmits('typeLoaded')
// 定义 props 接收 searchInfo
const props = defineProps({
  searchInfo: {
    type: Object,
    default: () => ({}),
  },
});

const { createMessage: msg } = useMessage();
const dictCode = 'gas_ccss_emission';

const [registerTable, { reload, setLoading, setColumns, setTableData }] = useTable({
  rowKey: 'id',
  columns: [],
  pagination: false,
  formConfig: {
    labelWidth: 120,
  },
  bordered: true,
  striped: true,
  actionColumn: {
    width: 120,
    title: '操作',
    dataIndex: 'action',
  },
});

function createActions(record) {
  if (!record.editable) {
    return [
      {
        label: '编辑',
        disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.id : false,
        onClick: handleEdit.bind(null, record),
      },
    ];
  }
  return [
    {
      label: '保存',
      onClick: handleSave.bind(null, record),
    },
    {
      label: '取消',
      onClick: handleCancel.bind(null, record),
    },
  ];
}

const updateList = () => {
  const [startTime, endTime] = year2.value;
  const formattedStart = startTime.format('YYYY-MM-DD');
  const formattedEnd = endTime.format('YYYY-MM-DD');
  getTgmplanNumDataSyn({ startDay: formattedStart, endDay: formattedEnd, planNum: "" });
};

const handleCancel = (record) => {
  currentEditKeyRef.value = '';
  record.onEdit?.(false, false);
};

const handleEdit = (record) => {
  currentEditKeyRef.value = record.key;
  record.onEdit?.(true);
};

const handleSave = async (record) => {
  currentEditKeyRef.value = '';
  const valid = await record.onValid?.();

  const deviceCustomDataValDTOList = dateList.value
    .map((dateStr, index) => {
      const key = String(index);
      const exists = record.hasOwnProperty(key);
      const value = exists ? record[key] : 0;
      return value !== 0 ? { date: dateStr, dailyEmission : value, remark: '' } : null;
    })
    .filter(item => item !== null);

  const remarkValue = record.remark || '';
  if (deviceCustomDataValDTOList.length > 0) {
    deviceCustomDataValDTOList[deviceCustomDataValDTOList.length - 1].remark = remarkValue;
    deviceCustomDataValDTOList[deviceCustomDataValDTOList.length - 1].totalStock = deviceCustomDataValDTOList[deviceCustomDataValDTOList.length - 1].dailyEmission ;
  }


  const data = {
    classifyId: record.type,
    data: deviceCustomDataValDTOList,
  };
  await ccssEmissionAddOrUpdate(data);
  const pass = await record.onEdit?.(false, true);
  msg.success({ content: '数据已保存', key: 'saving' });
  handleCancel(record);
  getTypeList();
};

const formatEditedData = (editedData, deviceCustomDataVal) => {
  const rowData = cloneDeep(deviceCustomDataVal);
  for (const key in editedData) {
    const [, subKey, field] = key.split(',');

    if (rowData[subKey]) {
      if (editedData[key] === null) {
        if (rowData[subKey].measureTime) {
          rowData[subKey][field] = 0;
        } else {
          delete rowData[subKey];
        }
      } else {
        rowData[subKey] = {
          ...rowData[subKey],
          [field]: editedData[key],
          measureTime: subKey,
        };
      }
    }
  }

  return Object.values(rowData);
};

onMounted(async () => {
  getTypeList();
});

// 监听 searchInfo 变化，触发查询
watch(
  () => props.searchInfo,
  (newValue, oldValue) => {
      console.log('searchInfo 变化，触发查询', newValue);
      getData();
  },
  { deep: true }
);

const formatHeader = (headerData) => {
  dateList.value = headerData;
  const headerList = [
    {
      title: '气体名称',
      dataIndex: 'chemicalName',
      width: 120,
      fixed: 'left',
    },


  ];

  headerData.forEach((item, index) => {
    headerList.push({
      title: `${dayjs(item).format('MM/DD')}`,
      dataIndex: index.toString(),
      width: 100,
      editRow: true,
      customRender: ({ text }) => {
        if (typeof text === 'number') {
          return text;
        } else {
          return text || '--';
        }
      },
    });
  });

  headerList.push(
    {
      title: '当前储罐液位',
      dataIndex: 'currentStorageLevel',
      width: 120,
      merge: true,
      editRow: true,
    },
    {
      title: '最近七天平均排放量',
      dataIndex: 'avgEmissionLast7Days',
      width: 120,

    },
    {
      title: '最近一周回收率',
      dataIndex: 'recoveryRateLast7Days',
      width: 120,
      merge: true,
    
    },
    {
      title: '预计可排放天数',
      dataIndex: 'estimatedEmissionDays',
      width: 120,
      merge: true,
    
    },
    {
      title: '储存罐最大容量',
      dataIndex: 'maximumCapacity',
      width: 120,
      merge: true,
    
    },
    {
      title: '保底液位',
      dataIndex: 'minimumLiquidLevel',
      width: 120,
      merge: true,
    
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 120,
      merge: true,
      // editRow: true,
    }



  );

  setColumns(headerList);
};

const formatTableData = (tableData) => {
  const data = tableData.map((item) => {
    const { data: itemData, ...others } = item;
    const record = reactive({ ...others });
    itemData.forEach((value, index) => {
      record[index] = value;
    });
    // 设置当前储罐液位的值为最后日期的值
    const lastDateIndex = dateList.value.length - 1;
    record.currentStorageLevel = itemData[lastDateIndex] || 0;
    return record;
  });

  setTableData(data);
};

const changeTabData = (itemName) => {
  let itemCode
  tabData.value.forEach((item) => {
    // item, itemName
    if (item.itemName == itemName) {
      itemCode = item.itemCode
    }
  });

  if (currentTab.value != 'CCSS用量图') {
    currentBtn.value = currentTab.value;
    classifyId.value = itemCode;
    getData();
  }
};

const getTypeList = async () => {
  const res = await getDictListByCode(dictCode);
  tabData.value = [
    ...res,
    // { itemCode: chart, itemName: 'CCSS用量图' },
  ];
  classifyId.value = res[0].itemCode;
  emit('typeLoaded', res)
  getData();
};

// ccssGas.vue 和 ccssGasbottom.vue 中
const getData = () => {
  // 检查 classifyId 是否有值
  if (!classifyId.value) {
    return;
  }
  setLoading(true);
  selectCcssEmissionData({
    startDay: props.searchInfo.startDay,
    endDay: props.searchInfo.endDay,
    queryType: props.searchInfo.queryType,
    classifyId: classifyId.value,
  })
    .then((e) => {
      console.log('数据获取成功', e);
      formatHeader(e.xaxisList);
      formatTableData(e.yaxisList);
    })
    .catch((e) => {
      console.error('数据获取出错:', e);
    })
    .finally(() => {
      setLoading(false);
    });
};

// 子组件重新加载数据的方法
const reloadData = () => {
  console.log("dasdasdasdasdasd");

  getData();
};

defineExpose({
  reloadData
});
</script>

<style scoped lang="scss">
.subitem-box {
  .subitem-btn {
    width: 112px;
    height: 28px;
    border: 1px solid rgb(208 212 223 / 100%);
    border-radius: 2px;
    background: #f3f7fb;
    box-shadow: none;
    color: #181818;
    font-size: 12px;
    font-weight: 400;
  }

  .subitem-btn-focus {
    width: 112px;
    height: 28px;
    border: 1px solid rgb(0 103 204 / 100%);
    border-radius: 2px;
    background: rgb(0 103 204 / 15%);
    box-shadow: none;
    color: #0067cc;
  }

  .ant-space {
    margin-bottom: 0 ! important;
  }
}

.content-box2 {
  display: flex;
  flex-direction: column;
  padding: 0 8px;
  background: #fff;
}

.content-box {
  display: flex;
  flex: 1;
  flex-direction: column;
  background: #fff;



  .table-box {
    flex: 1;
    flex-shrink: 0;
  }

  :deep(.ant-table-wrapper) {
    padding: 0;
  }
}
</style>